<template>
    <div>

        <!--        搜索信息区域      -->
        <el-card style="width: 100%; height: 10vh;">
            <el-form :inline="true">

                <el-form-item label="订单号" label-width="60px">
                    <el-input style="width: 160px" clearable v-model="searchNumber"
                              placeholder="请输入订单号号"></el-input>
                </el-form-item>

                <el-form-item label="用户名称" label-width="68px">
                    <el-autocomplete
                            class="inline-input"
                            v-model="searchUsername"
                            :fetch-suggestions="querySearchUserName"
                            placeholder="请输入用户名称"
                            @select="handleSelectUser"
                            style="width: 160px"
                            clearable
                    ></el-autocomplete>
                </el-form-item>


                <el-form-item label="店铺名称" label-width="68px">
                    <el-autocomplete
                            class="inline-input"
                            v-model="searchStoreName"
                            :fetch-suggestions="querySearchStoreName"
                            placeholder="请输入店铺名称"
                            @select="handleSelectStore"
                            style="width: 160px"
                            clearable
                    ></el-autocomplete>
                </el-form-item>


                <el-form-item label="下单时间">
                    <el-date-picker
                            style="width: 200px"
                            v-model="searchCreateTime"
                            type="daterange"
                            align="right"
                            unlink-panels
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            @change="handleDateChange"
                            :picker-options="pickerOptionsSearch">
                    </el-date-picker>
                </el-form-item>

                <el-button style="margin-left: 20px" type="primary" @click="searchByManyCondition" plain> 搜 索
                </el-button>
                <el-button @click="resetCondition"> 重 置</el-button>
            </el-form>

        </el-card>

        <!--        订单状态栏           -->
        <el-card style="width: 100%; height: 10vh;">
            <el-radio-group v-model="searchStatusStr" @change="handleStatusChange">
                <el-radio-button
                        v-for="item in statuss"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                ></el-radio-button>
            </el-radio-group>
        </el-card>

        <!--           订单信息表格        -->
        <el-card style="width: 100%; ">

            <!--          订单信息    标题-->
            <div slot="header" class="clearfix">
                <span style="font-weight: bold;font-size: 18px">订单信息</span>
                <el-button style="float: right;margin-right: 10px" type="danger" @click="deleteSelectOrders"> 删除选中
                </el-button>
                <!--                <el-button style="float: right;margin-right: 20px" type="primary" plain @click="showAddOrder">
                                    添加订单
                                </el-button>-->
                <el-button style="float: right;margin-right: 10px" type="primary" plain @click="selectAll"> 查询所有订单
                </el-button>

                <!-- 删除订单信息的弹窗 -->
                <el-dialog
                        title="提示"
                        :visible.sync="dialogVisible_deleteSelect"
                        width="30%">
                    <span>真的要删除选中的所有信息吗？</span>
                    <span slot="footer" class="dialog-footer">
                                        <el-button @click="dialogVisible_deleteSelect = false">取 消</el-button>
                                        <el-button type="danger" @click="handleDeleteorders">确 定</el-button>
                                    </span>
                </el-dialog>

            </div>


            <!--     订单信息列表    展示-->
            <!--     订单信息列表    展示-->
            <template>
                <el-table height="330"
                          :header-cell-style="{fontSize: '14px','text-align':'center'}"
                          :cell-style="{'text-align':'center'}"
                          :data="ordersProduct"
                          @selection-change="handleSelectCodeForTicket"
                          stripe
                          style="width: 100%">
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column width="50" label="序号" type="index" align="center"></el-table-column>
                    <el-table-column prop="orders.number" label="订单号" show-overflow-tooltip
                                     width="200px"></el-table-column>
                    <el-table-column prop="product.name" label="商品名称" width="170px"
                                     show-overflow-tooltip></el-table-column>

                    <el-table-column prop="orders.payment" label="订单金额" show-overflow-tooltip
                                     width="110px"></el-table-column>

                    <el-table-column label="订单状态" width="100">
                        <template slot-scope="scope">
                            <el-tag type="danger" v-if="scope.row.status===0">未付款</el-tag>
                            <el-tag type="success" v-if="scope.row.status===1">待发货</el-tag>
                            <el-tag v-if="scope.row.status===2">已发货</el-tag>
                            <el-tag type="warning" v-if="scope.row.status===3">待签收</el-tag>
                            <el-tag type="success" effect="dark" v-if="scope.row.status===4">已签收</el-tag>
                            <el-tag type="warning" v-if="scope.row.status===5">未评价</el-tag>
                            <el-tag type="success" effect="dark" v-if="scope.row.status===6">已评价</el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column label="支付状态" width="100">
                        <template slot-scope="scope">
                            <el-tag type="warning" v-if="scope.row.orders.payStatus===0">未支付</el-tag>
                            <el-tag type="success" effect="dark" v-if="scope.row.orders.payStatus===1">已支付</el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column label="支付类型" width="100">
                        <template slot-scope="scope">
                            <el-tag type="success" effect="dark" v-if="scope.row.orders.paymentType===0">微信</el-tag>
                            <el-tag effect="dark" v-if="scope.row.orders.paymentType===1">支付宝</el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column prop="orders.createTime" label="下单时间" show-overflow-tooltip
                                     width="150px"></el-table-column>

                    <el-table-column label="操作" width="100">

                        <template slot-scope="scope">
                            <el-button
                                    circle
                                    icon="el-icon-search"
                                    @click="handleInfoButton(scope.row)">
                            </el-button>


                            <!--         删除按钮    -->
                            <el-button type="danger" icon="el-icon-delete" circle
                                       @click="handleDeleteButton(scope.row)"></el-button>

                            <!-- 删除订单信息的弹窗 -->
                            <el-dialog
                                    title="提示"
                                    :visible.sync="dialogVisible_delete"
                                    width="30%">
                                <span style="display: flex;">真的要删除这条信息吗？</span>
                                <span slot="footer" class="dialog-footer">
                                        <el-button @click="dialogVisible_delete = false">取 消</el-button>
                                        <el-button type="danger" @click="handleDeleteOrder">确 定</el-button>
                                    </span>
                            </el-dialog>


                        </template>

                    </el-table-column>
                    <el-table-column label="发货">

                        <template slot-scope="scope">

                            <el-button
                                    size="mini"
                                    v-if="scope.row.status===1"
                                    type="primary" icon="el-icon-s-goods"
                                    @click="handleSendButton(scope.row)">发货
                            </el-button>


                            <el-tag v-if="scope.row.status!==1" style="width: 70px">
                                {{ scope.row.status === 1 ? '未发货' : '已发货' }}
                            </el-tag>


                        </template>
                    </el-table-column>


                </el-table>

            </template>

            <el-pagination
                    style="float: right;margin: 20px 0"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next"
                    background
                    :total="total">
            </el-pagination>
        </el-card>

    </div>
</template>

<script>

import dateUtil from '@/utils/dateUtil';


export default {
    name: 'Orders',
    data() {
        return {
            dialogFormVisible_edit: false,      // 编辑按钮弹出框
            dialogVisible_delete: false,        // 删除按钮弹出框
            dialogVisible_deleteSelect: false,  // 选中删除按钮弹出框
            dialogVisible_addOrder: false,      // 添加订单按钮弹出框

            userRestaurants: [],            // 存储所有所有用户
            storeRestaurants: [],          // 存储所有所有商家名称
            ordersProductId: '',             // 存储被删除订单的id
            ordersProduct: [],              // 存储订单信息

            orderId: '',             // 存储被删除订单的id
            ids: [],                 // 存储被选中订单的id
            orders: [],              // 存储订单信息

            searchNumber: '',       // 存储搜索的订单号
            searchUsername: '',          // 存储搜索的用户名称
            searchUserId: '',            // 存储用户的ID
            searchStoreId: '',            // 存储用户的ID
            searchStoreName: '',         // 存储搜索的订单名称
            searchCreateTime: '',      // 存储搜索的创建时间
            startTime: '',            // 存储搜索的开始时间
            endTime: '',              // 存储搜索的结束时间
            searchStatus: '-1',       // 存储搜索的状态
            searchStatusStr: '全部',       // 存储搜索的状态
            // 搜素的日期选择器
            pickerOptionsSearch: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },

            // 订单状态：0已取消；1未付款；2已付款；3待发货；4已发货；5待签收；6已签收；7未评价；
            statuss: [{             // 存储所有状态
                value: -1,
                label: '全部'
            }, {
                value: 1,
                label: '未付款'
            }, {
                value: 2,
                label: '已付款'
            }],

            // 支付状态：0未支付；1已支付
            payStatuss: [{             // 存储支付状态
                value: 0,
                label: '未支付'
            }, {
                value: 1,
                label: '已支付'
            }],

            // 付款类型:0微信，1支付宝
            paymentTypes: [{             // 存储付款类型
                value: 0,
                label: '微信'
            }, {
                value: 1,
                label: '支付宝'
            }],

            currentPage: 1,          // 当前页码
            pageSizes: [5, 10, 50, 100], // 每页显示条数
            pageSize: 5,             // 每页显示条数
            total: 0,                // 订单总数


        }
    },
    mounted() {
        this.selectByPage()

        this.loadAllStore()
        this.loadAllUser()
    },


    methods: {

        // 输入建议的查询函数
        querySearchUserName(queryString, cb) {
            var restaurants = this.userRestaurants;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        querySearchStoreName(queryString, cb) {
            var restaurants = this.storeRestaurants;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        // 带搜索建议的输入框被选中后的响应函数
        handleSelectUser(item) {
            // console.log(item);
            this.searchUserId = item.id
        },
        // 带搜索建议的输入框被选中后的响应函数
        handleSelectStore(item) {
            // console.log(item);
            this.searchStoreId = item.id
        },
        // 加载所有的店铺
        loadAllStore() {
            this.$request.get('/store/loadAllStore').then(res => {
                if (res.code === '200') {
                    this.storeRestaurants = res.data;
                    // 遍历restaurants,让this.restaurants中的数据格式化name参数变为value
                    this.storeRestaurants.forEach((restaurant) => {
                        restaurant.value = restaurant.name;
                        // delete restaurant.name;
                    });
                } else {
                    this.$message.error(res.msg);
                }
            })
        },
        // 加载所有的用户
        loadAllUser() {
            this.$request.get('/user/loadAllUser').then(res => {
                if (res.code === '200') {
                    this.userRestaurants = res.data;
                    // 遍历restaurants,让this.restaurants中的数据格式化name参数变为value
                    this.userRestaurants.forEach((restaurant) => {
                        restaurant.value = restaurant.name;
                        // delete restaurant.name;
                    });
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        // 移除表单的校验
        clearcheck(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].clearValidate()
            }
        },

        // 查询所有订单
        selectAll() {
            this.currentPage = 1
            this.selectByPage()
        },

        // 删除选中二次确认
        handleDeleteorders() {
            this.dialogVisible_deleteSelect = false;

            if (this.ids.length > 0) {
                // 删除选中
                this.$request.post('/ordersProduct/deleteByIds', this.ids).then(res => {
                    if (res.code === '200') {
                        this.$message.success('删除成功');
                        // 刷新数据
                        this.searchByManyConditionNoMsg()
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            } else {
                this.$message.info('请选择要删除的订单');
            }
        },

        // 删除选中二次提醒
        deleteSelectOrders() {
            // 显示二次提醒弹窗
            this.dialogVisible_deleteSelect = true;
        },

        // 获取选中的订单id，
        // 并存储到 ids 数组中
        handleSelectCodeForTicket(val) {
            this.ids = val.map((item) => item.id);
        },


        // currentPage 改变时会触发
        handleCurrentChange(val) {
            // 获取  当前页 和 页面大小  currentPage、pageSize
            this.currentPage = val;

            // 发送请求获取相应数量的数据
            this.searchByManyConditionNoMsg()
        },


        //  pageSize 改变时会触发
        handleSizeChange(val) {
            // 获取  当前页 和 页面大小  currentPage、pageSize
            this.pageSize = val;
            this.currentPage = 1;

            // 发送请求获取相应数量的数据
            this.searchByManyConditionNoMsg()
        },


        // 条件查询
        searchByManyCondition() {

            // 处理时间段信息
            if (this.searchCreateTime !== '' && this.searchCreateTime !== null) {
                this.startTime = dateUtil.formatDate(this.searchCreateTime[0])
                this.endTime = dateUtil.formatDate(this.searchCreateTime[1])
            } else {
                this.startTime = '1000-01-01 00:00:00'
                this.endTime = '9999-12-31 23:59:59'
            }
            // 对应状态值
            let statuss = JSON.parse(JSON.stringify(this.statuss))
            statuss.forEach((item, index) => {
                if (item.label === this.searchStatusStr) {
                    this.searchStatus = item.value
                }
            })
            // 如果状态为-1，则设为null，这样的话，我后台直接调用一个方法就行
            if (this.searchStatus === -1 || this.searchStatusStr === '全部') {
                this.searchStatus = ''
            }
            // 如果状态未选择的话，调用A接口
            // 否则调用B接口
            // A接口不包括状态参数
            // B接口包括状态参数
            this.$request.post('/ordersProduct/selectByManyCondition?currentPage=' + this.currentPage
                + '&pageSize=' + this.pageSize
                + '&number=' + this.searchNumber
                + '&storeId=' + this.searchStoreId
                + '&userId=' + this.searchUserId
                + '&startTime=' + this.startTime
                + '&endTime=' + this.endTime
                + '&status=' + this.searchStatus
            ).then(res => {
                // console.log(res)
                if (res.code === '200') {
                    this.ordersProduct = res.data.list
                    this.total = res.data.total
                    this.$message.success("查询成功");
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        // 条件查询 用来刷新数据不提示
        searchByManyConditionNoMsg() {
            // 处理时间段信息
            // console.log(this.searchCreateTime)
            // 处理时间段信息
            if (this.searchCreateTime !== '' && this.searchCreateTime !== null) {
                this.startTime = dateUtil.formatDate(this.searchCreateTime[0])
                this.endTime = dateUtil.formatDate(this.searchCreateTime[1])
            } else {
                this.startTime = '1000-01-01 00:00:00'
                this.endTime = '9999-12-31 23:59:59'
            }
            // 对应状态值
            let statuss = JSON.parse(JSON.stringify(this.statuss))
            statuss.forEach((item, index) => {
                if (item.label === this.searchStatusStr) {
                    this.searchStatus = item.value
                }
            })
            // 如果状态为-1，则设为null，这样的话，我后台直接调用一个方法就行
            if (this.searchStatus === -1 || this.searchStatusStr === '全部') {
                this.searchStatus = ''
            }
            this.$request.post('/ordersProduct/selectByManyCondition?currentPage=' + this.currentPage
                + '&pageSize=' + this.pageSize
                + '&number=' + this.searchNumber
                + '&storeId=' + this.searchStoreId
                + '&userId=' + this.searchUserId
                + '&startTime=' + this.startTime
                + '&endTime=' + this.endTime
                + '&status=' + this.searchStatus
            ).then(res => {
                // console.log(res)
                if (res.code === '200') {
                    this.ordersProduct = res.data.list
                    this.total = res.data.total
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        // 分页查找
        selectByPage() {
            this.$request.post('/ordersProduct/selectByPage?currentPage=' + this.currentPage
                + '&pageSize=' + this.pageSize
            ).then(res => {
                if (res.code === '200') {
                    // console.log(res)
                    this.ordersProduct = res.data.list;
                    this.total = res.data.total;
                    // console.log(this.ordersProduct)
                    // this.$message.success('查询成功');
                } else {
                    this.$message.error(res.msg);
                }
            })
        },


        // 重置搜索条件
        resetCondition() {
            this.searchNumber = ''
            this.searchUsername = ''
            this.searchStoreName = ''
            this.searchStatus = '-1'
            this.searchStatusStr = '全部'
            this.currentPage = 1
            this.pageSize = 5
            // 刷新获取订单信息
            this.selectByPage()
            this.$message
                .success('重置成功')
        },


        // 删除按钮二次提醒
        handleDeleteButton(ordersProduct) {
            this.dialogVisible_delete = true
            this.orderId = ordersProduct.id
        },


        // 删除当前订单
        handleDeleteOrder() {
            this.dialogVisible_delete = false;
            this.$request.post('/ordersProduct/deleteById/' + this.orderId).then(res => {
                if (res.code === '200') {
                    this.$message.success('删除成功');
                    this.orderId = ''
                    // 重新加载数据
                    this.searchByManyConditionNoMsg()
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        handleSendButton(ordersProduct) {
            // this.dialogVisible_delete = true
            let ordersProductId = ordersProduct.id
            let productId = ordersProduct.product.id
            // console.log(ordersProductId)
            // console.log(productId)
            //  实现发货请求：
            this.$request.post('/ordersProduct/send?id=' + ordersProductId).then(res => {
                if (res.code === '200') {
                    this.$message.success('发货成功')
                    this.searchByManyConditionNoMsg()
                } else {
                    this.$message.error(res.msg)
                }
            })
        },

        handleInfoButton(ordersProduct) {
            console.log(ordersProduct)
            // let ordersProductId = ordersProduct.id
            this.$router.push({name: 'orderInfoManager', params: {ordersProduct: ordersProduct}})
        },

        // 解决elementUI中时间选择器的问题，使得时间选择器可以清空
        handleDateChange(value) {
            // 当日期改变时的处理函数
            // 在这里你可以根据需要处理日期的值
            // 例如，如果不想让清空操作将日期设置为null，可以在这里进行判断
            if (value === null) {
                // 当清空日期时，不更新pickedDate，保持原值
                // 如果需要在清空时设置日期为特定值（比如空字符串），可以在此处设置
                this.searchCreateTime = ''
                return;
            }
            // 在其他情况下，将值更新为选择的日期
            this.searchCreateTime = value;
        },


        // 直接点击住状态的是哦后需要把currentpage重置
        handleStatusChange() {
            this.currentPage = 1;
            this.searchByManyCondition()
        }

    }
}
</script>


<style>
.el-dialog__body {
    padding: 10px 30px;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

input[type="number"] {
    -moz-appearance: textfield;
}


</style>